#include "../include/conf.h"

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

Config* Config::instance_ = NULL;

Config& Config::get_instance() {
  if (!instance_) {
    pthread_mutex_lock(&mutex);
    if (!instance_)
      instance_ = new Config;
    pthread_mutex_unlock(&mutex);
  }
  return *instance_;
}

Config::Config() {
  std::ifstream fin("./conf/config.conf", std::ifstream::in);
  if (!fin) {
    std::cerr << "open config file ERROR!" << std::endl;
    exit(0);
  } else {
    std::string line;
    dict_.clear();
    while (getline(fin, line)) {
      trim(line);
      if (line.empty() || line[0] == '#')
        continue;
      else {
        std::string::size_type pos = line.find('=');
        if (pos != std::string::npos) {
          std::string key = line.substr(0, pos);
          std::string value = line.substr(pos + 1);
          trim(key);
          trim(value);
          this->dict_[key] = value;
        }
      }
    }
  }
  fin.close();
}

Config::~Config() {

}

std::string Config::get(const std::string& key) {
  std::map<std::string, std::string>::iterator it = dict_.find(key);
  if (it != dict_.end())
    return it->second;
  else
    return "";
}
